package com.briup.es.service.impl;

import com.briup.es.config.auth.SecurityUserContext;
import com.briup.es.config.exception.ServiceException;
import com.briup.es.config.response.ResultCode;
import com.briup.es.domain.vo.BookDetailVO;
import com.briup.es.domain.vo.BookVO;
import com.briup.es.mapper.BookMapper;
import com.briup.es.mapper.CollectMapper;
import com.briup.es.service.CollectService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class CollectServiceImpl implements CollectService {

    private final CollectMapper collectMapper;
    private final BookMapper bookMapper;

    @Override
    public List<BookVO> listCollect() {
        // 从认证上下文中获取 当前登录用户的 id
        Integer userId = SecurityUserContext.userId();
        return collectMapper.queryCollectByUserId(userId);
    }

    @Override
    public void addCollect(Integer bookId) {
        Integer userId = SecurityUserContext.userId();
        BookDetailVO detailVO = bookMapper.queryById(bookId, userId);
        if (detailVO==null){
            throw new ServiceException(ResultCode.BOOK_IS_NOT_EXISTS);
        }

        // 如果当前用户已经收藏过该商品，那么直接返回
        if (detailVO.getCollect()){
            return;
        }

        // 如果未收藏过，那么添加收藏记录
        collectMapper.addCollect(userId,bookId);
    }

    @Override
    public void batchCancelCollect(List<Integer> bookIds) {
        if (CollectionUtils.isEmpty(bookIds)){
            throw new ServiceException(ResultCode.PARAMS_IS_INVALID);
        }

        // 根据图书id批量取消当前用户的收藏
        Integer userId = SecurityUserContext.userId();
        /*for (Integer bookId : ids) {
            collectMapper.deleteCollect(userId,bookId);
        }*/
        collectMapper.batchDeleteCollect(userId,bookIds);
    }
}
